package org.gp.demo.lucene.demo;

import java.io.File;
import java.io.IOException;

import junit.framework.TestCase;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class LunceneDemo_1 extends TestCase {
	Logger log = Logger.getLogger(LunceneDemo_1.class);

	public void testWriterIndex() {
		Analyzer an = new StandardAnalyzer(Version.LUCENE_CURRENT);

		try {
			// Directory directory = new RAMDirectory();
			Directory directory = FSDirectory.open(new File(
					"G:/myjava/demo/src/org/gp/lucene/demo/indexDir"));
			IndexWriter iw = new IndexWriter(directory, an, true,
					new IndexWriter.MaxFieldLength(25000));
			Document doc = new Document();
			String text = "This is the text to be indexed.";
			doc.add(new Field("fieldname", text, Store.YES, Index.ANALYZED));
			iw.addDocument(doc);
			iw.close();

			directory.close();
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void testSearcher() {
		try {
			Analyzer an = new StandardAnalyzer(Version.LUCENE_CURRENT);
			Directory directory = FSDirectory.open(new File(
					"G:/myjava/demo/src/org/gp/lucene/demo/indexDir"));
			IndexSearcher is = new IndexSearcher(directory, true);
			QueryParser qp = new QueryParser(Version.LUCENE_CURRENT,
					"fieldname", an);
			Query query = qp.parse("text");
			ScoreDoc[] hits = is.search(query, null, 1000).scoreDocs;
			log.info(hits.length);
			for (int i = 0; i < hits.length; i++) {
				Document hitDoc = is.doc(hits[i].doc);
				log.info(hitDoc.get("fieldname"));
			}
			is.close();
			directory.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
